import { ArrowLeftOutlined, CheckOutlined, ClockCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Popover, Select } from 'antd';
import 'antd/dist/antd.css';
import moment from 'moment';
import queryString from 'query-string';
import React from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { FMT_YMD } from '../common/constant';
import Home from '../common/home';
import http from '../common/http';
import MyMarkdown from "../common/MyMarkdown";

const { TextArea } = Input
const { Option } = Select

class NoteItemForm extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: false,
            id: null,
            typeId: null,
            title: "",
            content: "",
            types: [{ id: 1, name: "test" }],
            reviewList: []
        }
    }

    componentDidMount() {
        var search = this.props.location.search
        let data = queryString.parse(search)
        var { sign, typeId, noteId } = data || {}
        this.setState({ sign })
        if (noteId) {
            this.fetchNoteInfo(noteId)
            http.get("/api/note/review/findList?noteId=" + noteId)
                .then(res => {
                    this.setState({ reviewList: res.data })
                })
        }
        if (typeId)
            this.setState({ typeId }, this.fetchTypes)
        else
            this.fetchTypes()
    }
    fetchNoteInfo = (noteId) => {
        this.setState({ loading: true })
        http.get("/api/note/note/find-one/" + noteId)
            .then(res => {
                this.setState({
                    loading: false,
                    ...res.data
                }, () => {
                    this.fetchTypes()
                    this.props.form.setFieldsValue({
                        title: res.data.title,
                        content: res.data.content,
                    })
                })
            })
    }
    fetchTypes = () => {
        http.get("/api/note/type/find-all")
            .then(res => {
                let types = res.data
                this.setState({ types }, () => {
                    this.props.form.setFieldsValue({
                        typeId: this.state.typeId,
                    })
                })
            })
    }

    onTitleChange = (e) => { // 为了预览
        let title = e.target.value
        this.setState({ title })
    }
    onContentChange = (e) => { // 为了预览
        let content = e.target.value
        this.setState({ content })
    }
    onCancel = (e) => {
        this.onBackOrClose()
    }
    onBackOrClose = () => {
        if (this.state.sign == "new")
            window.close()
        else
            this.props.navigate(-1)
    }
    handleSubmit = (e) => {
        this.props.form.validateFields()
            .then(values => {
                const obj = { id: this.state.id, typeId: this.state.typeId, ...values }
                http.post("/api/note/note/save", obj)
                    .then(res => {
                        message.success(`【${this.state.title}】保存成功`, 1)
                        this.onBackOrClose()
                    })
            })
            .catch(err => console.info("err"))
    }

    findReviewList = () => {
        http.get("/api/note/review/findList?noteId=" + this.state.id)
            .then(res => {
                this.setState({ reviewList: res.data })
            })
    }
    resetReviewPlan = () => {
        http.post("/api/note/review/resetReviewPlan?noteId=" + this.state.id)
            .then(res => {
                message.success(`复习计划重置成功`, 1)
                this.setState({
                    reviewVisible: false,
                })
                this.findReviewList()
            })
    }
    handleVisibleChange = (visible) => {
        this.setState({ reviewVisible: visible });
    }

    formatDate = (date) => {
        var ymd = moment(date).format(FMT_YMD)
        var week = moment(date).format("dddd")
        return ymd + " " + week.substring(2);
    }

    render() {
        // const { getFieldDecorator } = this.props.form
        return (
            <div>
                <Home />

                <div>
                    <div style={{ width: '50%', float: 'left', height: '100%', }}>
                        <Form form={this.props.form} layout="vertical" hideRequiredMark >
                            <Form.Item name="typeId" label="类型" rules={[{ required: true, message: '请选择类型' }]}>
                                <Select showSearch placeholder="请选择类型"
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }>
                                    {
                                        this.state.types.map(type => {
                                            return (<Option key={type.id}>{type.name}</Option>)
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
                                <Input placeholder="请输入标题" onChange={this.onTitleChange} />
                            </Form.Item>
                            <Form.Item name="content" label="内容（Morkdown 格式）">
                                <TextArea placeholder="请输入内容"
                                    autoSize={{ minRows: 15 }} // , maxRows: 40
                                    onChange={this.onContentChange} />
                            </Form.Item>
                        </Form>
                        <Button onClick={this.onCancel} style={{ marginRight: 8 }}> <ArrowLeftOutlined /> 取消 </Button>
                        <Button onClick={this.handleSubmit} type="primary"> <CheckOutlined /> 提交 </Button>
                    </div>

                    <div style={{
                        position: 'absolute', right: 0, bottom: 0,
                        width: '50%', float: 'right', height: '100%',
                        borderLeft: '1px solid #e9e9e9', padding: '10px 16px',
                        background: '#fff', textAlign: 'left',
                    }}>
                        <h4 style={{ marginBottom: 16 }}>
                            <b>{this.state.title}</b>
                            <Popover title="复习计划"
                                visible={this.state.reviewVisible}
                                onVisibleChange={this.handleVisibleChange}
                                content={
                                    <div>
                                        <Button type="primary" onClick={this.resetReviewPlan}> <SyncOutlined /> 重置复习计划 </Button>
                                        <p />
                                        {
                                            this.state.reviewList.map(reviewObj => {
                                                return (
                                                    <div key={reviewObj.id}>
                                                        第 {reviewObj.frequency} 次
                                                        （{this.formatDate(reviewObj.reviewDate)}）：{reviewObj.status == 1 ? "未复习" : "已复习"}
                                                    </div>
                                                )
                                            })
                                        }
                                    </div>
                                }>
                                {
                                    this.state.id ? (
                                        <ClockCircleOutlined style={{ marginLeft: 10, color: '#08c' }} title="复习计划" />
                                    ) : null
                                }

                            </Popover>
                        </h4>
                        <MyMarkdown source={this.state.content} />
                    </div>

                </div>
            </div>
        );
    }
}

// export default NoteItemForm
function WithNavigate(props) {
    let navigate = useNavigate(); // 用作组件返回时才有用
    let location = useLocation();
    let [form] = Form.useForm();
    return <NoteItemForm {...props} navigate={navigate} location={location} form={form} />
}
export default WithNavigate